<?php
/**
 * $Id:$
 *
 * FGS is the legal property of its developers, whose names are too numerous
 * to list here.  Please refer to the COPYRIGHT file distributed with this
 * source distribution.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */ 


class fgsUsers {

	var $cache = array();

	/**
	 * allowRegistration() 
	 */
	function allowRegistration() {
		return true;
	}
	
	/**
	 * add() add an user
	 */
	function add($login, $password, $email, $website, $avatar, $is_deleted, $is_admin) {
		if (fgsUsers::get($login))
			return false;
		$query = sprintf('
			INSERT INTO fgs_users
			SET 
				login = "%s",
				password = "%s",
				email = "%s",
				avatar = "%s",
				is_deleted = %d,
				is_admin = %d,
				dt_create = NOW()',
			fgsSql::escapeStr($login),
			fgsSql::escapeStr($password),
			fgsSql::escapeStr($email),
			fgsSql::escapeStr($website),
			$is_deleted ? 1 : 0,
			$is_admin ? 1 : 0
		);

		$sql = fgs::sql();
		return $sql->query($query) ? true : false;

	}

	/**
	 * update() update an user
	 */
	function update($id, $login, $password, $email, $website, $avatar, $is_deleted, $is_admin) {
		$query = sprintf('
			UPDATE fgs_users
			SET 
				login = "%s",
				password = "%s",
				email = "%s",
				avatar = "%s",
				is_deleted = %d,
				is_admin = %d
			WHERE 
				id = %d',
			fgsSql::escapeStr($login),
			fgsSql::escapeStr($password),
			fgsSql::escapeStr($email),
			fgsSql::escapeStr($website),
			$is_deleted ? 1 : 0,
			$is_admin ? 1 : 0,
			$id
		);

		$sql = fgs::sql();
		return $sql->query($query) ? true : false;

	}

	/**
	 * checkLogin() 
	 * $param login login of user
	 * $param password password of user
	 */
	function checkLogin($login, $password) {
		$query = sprintf('
			SELECT login
			FROM fgs_users
			WHERE 
				login = "%s"
				AND password = "%s"
				AND NOT is_deleted',
			fgsSql::escapeStr($login),
			fgsSql::escapeStr($password)
		);

		$sql = fgs::sql();
		$sql->query($query);

		return $sql->nbrows();
	}

	/**
	 * createSession() add a session for user
	 * @param login valid login of user
	 */
	function createSession($login) {
		
		// create sid
		$user_sid = md5(uniqid('k'));

		// construct query
		$query = sprintf('
			INSERT INTO fgs_sessions
			SET
				login = "%s",
				user_sid = "%s",
				user_ip = "%s",
				dt_create = NOW(),
				dt_lastaccess = NOW()', 
			fgsSql::escapeStr($login), 
			fgsSql::escapeStr($user_sid), 
			fgsSql::escapeStr(fgsUtils::GetIp())
		);
		
		$sql = fgs::sql();
		$sql->query($query);

		return $user_sid;
	}
	
	/**
	 * deleteSession() delete session for user
	 * @param login valid login of user
	 * @param sid valid sessionid of user
	 */
	function deleteSession($login, $user_sid) {
		
		// construct query
		$query = sprintf('
			DELETE FROM fgs_sessions
			WHERE
				login = "%s"
				AND user_sid = "%s"',
			fgsSql::escapeStr($login),
			fgsSql::escapeStr($user_sid)
		);
		
		$sql = fgs::sql();
		$sql->query($query);

		return $sql->affrows();
	}
	
	/**
	 * get() return users
	 * @param id retreive information about 'id' player (optional)
	 */
	function get($id = null) {

		if ($id != null && isset($this->cache[$id])) 
			return $this->cache[$id];

		$query = sprintf('
			SELECT *
			FROM fgs_users
			%s
			ORDER BY login',
			$id != null ? sprintf('WHERE login = "%s"', fgsSql::escapeStr($id)) : ''
		);
				
		$sql = fgs::sql();
		$sql->query($query);
		if (!$sql->nbrows())
			return false;
		$infos = $sql->fetchAll();
		if ($id != null) {
			$infos = current($infos);
			if ($this)
				$this->cache[$id] = $infos;
		}
		return $infos;
	}

	/**
	 * getById() return an user by id
	 * @param id retreive information about 'id' player (optional)
	 */
	function getById($id = null) {

		if ($id != null && isset($this->cache[$id])) 
			return $this->cache[$id];

		$query = sprintf('
			SELECT *
			FROM fgs_users
			%s
			ORDER BY login',
			$id != null ? sprintf('WHERE id = %d', $id) : ''
		);
				
		$sql = fgs::sql();
		$sql->query($query);
		if (!$sql->nbrows())
			return false;
		return $sql->getline();
	}

	/**
	 * getOnline() return users who is online
	 */
	function getOnline() {

		$query = sprintf('
			SELECT *
			FROM fgs_users
			WHERE UNIX_TIMESTAMP(dt_lastactivity) < 300'
		);

		$sql = fgs::sql();
		$sql->query($query);

		return $sql->fetchAll();
	}

	/**
	 * enable() enable access for an user
	 */
	function enable($id, $enable) {
		$query = sprintf('UPDATE fgs_users SET is_deleted = %d WHERE id = %d', $enable ? 0 : 1, $id);
		$sql = fgs::sql();
		return $sql->query($query) ? true : false;
	}

	/**
	 * checkSession() check if session of an user exist
	 * @param login valid user login
	 * @param sid session user to verify
	 * @param salt salt to make session uniq
	 */
	function checkSession($login, $sid, $salt) {
		
		$query = sprintf('
			SELECT fgs_users.login, fgs_users.id
			FROM fgs_sessions
			LEFT JOIN fgs_users
				ON fgs_users.login = fgs_sessions.login
			WHERE
				fgs_sessions.login = "%s"
				AND SHA1(CONCAT(fgs_sessions.user_sid, "%s")) = "%s"',
				fgsSql::escapeStr($login),
				fgsSql::escapeStr($salt),
				fgsSql::escapeStr($sid)
		);

		$sql = fgs::sql();
		$sql->query($query);

		if ($sql->nbrows() != 1)
			return false;

		return $sql->getline();
	}

	/** 
	 * getIdFromSaltAndCram() 
	 * @param salt
	 * @param cram
	 * @return id of user
	 */
	function getIdFromSaltAndCram($salt, $cram) {

		$query = sprintf('
			SELECT users.id
			FROM fgs_sessions
			LEFT JOIN users
				ON users.login = fgs_sessions.login
			WHERE SHA1(CONCAT(fgs_sessions.user_sid, "%s")) = "%s"',
			fgsSql::escapeStr($salt),
			fgsSql::escapeStr($cram)
		);

		$sql = fgs::sql();
		$sql->query($query);
		if ($sql->nbrows() != 1)
			return false;
		
		$res = $sql->getline();
		return $res['id'];

	}

	/**
	 * setCurrentMatch() set current match
	 * @param match_id id of match
	 * @param login valid user login
	 * @param sid session user to verify
	 * @param salt salt to make session uniq
	 */
	function setCurrentMatch($match_id, $login, $sid, $salt) {

		$query = sprintf('
			UPDATE fgs_sessions
			SET 
				id_fgsd_game = %s,
				dt_lastaccess = NOW()
			WHERE login = "%s"
				AND SHA1(CONCAT(user_sid, "%s")) = "%s"
			ORDER BY id DESC
			LIMIT 1',
			is_null($match_id) ? 'NULL' : (int)$match_id,
			fgsSql::escapeStr($login),
			fgsSql::escapeStr($salt),
			fgsSql::escapeStr($sid)
		);

		$sql->query($query);

		return true;
	}
	
	/**
	 * updateEntries() update user attribute
	 * @param fgsd valid array of fgsd attributes
	 * @param login player login
	 * @param sid player sid
	 * @param salt player salt
	 * @param values array of key/values
	 * @param timestamp current timestamp
	 */
	function updateEntries($fgsd, $login, $sid, $salt, $values, $timestamp) {
		
		// prepare variables
		$query_args = array();
		$sql = fgs::sql();

		$user = fgsUsers::checkSession($login, $sid, $salt);
		if ($user === false)
			return false;

		foreach ($values as $k => $v) {
			$query_args[] = array(
				'id_user' => $user['id'],
				'key' => $k,
				'value' => $v,
			);
		}

		if (count($query_args)) {

			// construct query
			$query = 'REPLACE INTO fgs_users_entry(`id_user`, `key`, `value`) VALUES';
			$query2 = array();

			foreach ($query_args as $elt) {
				$query2[] = sprintf('("%d", "%s", "%s")',
					$elt['id_user'],
					fgsSql::escapeStr($elt['key']),
					fgsSql::escapeStr($elt['value'])
				);
			}

			$query .= implode(', ', $query2);

			$sql->query($query);

			$affrows = $sql->affrows();
			if ($affrows > 0)
				fgsLog::log(1, sprintf('[%s] change %d entries for player %d', $fgsd['fgsd_name'], count($query_args), $user['id']));
			else 
				fgsLog::log(1, sprintf('[%s] no change when update player %d entries', $fgsd['fgsd_name'], $user['id']));
				
			return $affrows;

		}
		
		return 0;


	}


}

?>
